define([ 'jquery', 'underscore', 'backbone', 'bootstrap','wysihtml5','bt-wysihtml5',
         'text!templates/IdearModuleTemplate.jst','BaseModule'],
		function($, _, Backbone, bt,wysi,btwysi,IdearModuleTemplate,BaseModule) {
	        var idearContext={},eventsName={
	        	shiftPanel:"IdearModule:shiftPanel",
	        	refreshComment:"IdearModule:refreshComment"
	        };
	        _.extend(idearContext,Backbone.Events);
	        
	        var idearModuleUrl={
	        		idear:BaseModule.WebRoot+"idear",
	        		idearLatest:BaseModule.WebRoot+"idear/Latest",
	        		comment:BaseModule.WebRoot+"comment",
	        		commentList:BaseModule.WebRoot+"comment/list"
	        };
	        var IdearRouter=Backbone.Router.extend({
	        	routes:{
	        		"IdearModule/idear/newIdear":"newIdear",
	        		"IdearModule/idear/showIdear/:idearId":"showIdear",
	        		"IdearModule/idear/idearList":"idearList"
	        	},
	        	newIdear:function(){
	        		idearContext.trigger(eventsName.shiftPanel,"IdearCreation");
	        	},
	        	showIdear:function(idearId){
	        		idearContext.trigger(eventsName.shiftPanel,"IdearShown",idearId);
	        	},
	        	idearList:function(){
	        		idearContext.trigger(eventsName.shiftPanel,"IdearList");
	        	}
	        	
	        });
	        var ListIdearModel=BaseModule.BaseModel.extend({
				
			});
	        var CommentModel=BaseModule.BaseModel.extend({
			  	urlRoot:idearModuleUrl.comment,
			  	validate:function(attrs){
					 if(attrs.comment == ''){
						   return "评论不能为空!";
					   }
				}
			});
			
	        var IdearModel=BaseModule.BaseModel.extend({
	        	urlRoot:idearModuleUrl.idear,
				validate:function(attrs){
					 if(attrs.title == ''){
						   return "title can not be null";
					   }
					   if(attrs.problem == ''){
						   return "problem can not be null";
					   }
					   if(attrs.solution == ''){
						   return "solution can not be null";
					   }
				}
			});
	        var IdearList=BaseModule.BaseCollection.extend({
				url:idearModuleUrl.idearLatest,
				model:ListIdearModel,
				initialize:function(){
				}
			});
			var CommentList=BaseModule.BaseCollection.extend({
				model:CommentModel,
				idearId:0,
				url:function(){
					return idearModuleUrl.commentList+"/"+this.idearId;
				}
			});
			
			var IdearModule = Backbone.View.extend({
				tagName:"div",
				template:_.template(IdearModuleTemplate),
				initialize : function() {
					Backbone.Events.on("shiftModule",this.open,this);
					this.sideBar=new SideBarView();
					this.listIdearPanel=new ListIdearPanel();
					this.createIdearPanel=new CreateIdearView();
					this.idearPanel=new IdearShowPanel();
					this.router =new IdearRouter();
					idearContext.on(eventsName.shiftPanel,this.show,this);
				},
				render:function(){
					if(this.rendered){
						return this;
					}
					$(this.el).html(this.template({"tempId":"BaseFrameWork","data":null}));
					this.$('#idearSidebarDiv').html(this.sideBar.render().el);
					this.$('#idearsCenter').html(this.listIdearPanel.render().el);
					this.$('#idearsCenter').append(this.createIdearPanel.el);
					this.$('#idearsCenter').append(this.idearPanel.el);
					this.rendered=true;
					return this;
				},
				open:function(name){
					name == "idear" ? this.render().$el.fadeIn(): this.$el.hide();
				},
				show:function(name){
					$('#topNavUL>li').removeClass("active");
			 		$('#topNavUL>li:eq(1)').addClass("active")
			 		Backbone.Events.trigger("shiftModule","idear");
				}
			});

			var SideBarView=Backbone.View.extend({
				tagName:"div",
				template:_.template(IdearModuleTemplate),
				events:{
				},
				initialize:function(){
				},
				render:function(){
					$(this.el).html(this.template({"tempId":"Sidebar","data":null}));
					return this;
				}
			});
			
			var ListIdearPanel=Backbone.View.extend({
				tagName:"div",
				template:_.template(IdearModuleTemplate),
				initialize: function(){
					this.idearList=new IdearList();
					this.idearList.bind('add',this.addOne,this);
					this.idearList.bind('reset',this.addAll,this);
					idearContext.on(eventsName.shiftPanel,this.open,this);
			    },
			    render:function(){
			    	$(this.el).html(this.template({"tempId":"IdearList","data":null}));
			    	this.idearList.fetch();
			    	return this;
			    },
			    addOne:function(iModel){
			    	var itemView=new ListIdearItemView({model:iModel});
			    	this.$('ul').append(itemView.render().el);
			    },
			    addAll:function(){
			    	this.$('ul').empty();
			    	this.idearList.each(this.addOne,this);
			    },
			    open:function(name){
			    	name == "IdearList" ? this.$el.show(): this.$el.hide();
			    }
			});
			var ListIdearItemView=Backbone.View.extend({
				 tagName:"li",
				 template:_.template(IdearModuleTemplate),
			     events:{
			     },
			     initialize: function (){
			     },
			     render:function(){
			    	 $(this.el).html(this.template({"tempId":"IdearListItem","data":this.model.toJSON()}));
			    	 return this;
			     }
			});
			
			var CreateIdearView=Backbone.View.extend({
				tagName:"div",
				template:_.template(IdearModuleTemplate),
				 initialize: function (){
					 idearContext.on(eventsName.shiftPanel,this.open,this);
				 },
				 events:{
					 'click #submitIdearBtn':"submitIdear"
				 },
				 render:function(){
					$(this.el).html(this.template({"tempId":"CreateIdear","data":null}));
					this.$('#problem').css({"width":580,'height':150});
					this.$('#problem').wysihtml5();
					this.$('#solution').css({"width":580,'height':200});
					this.$('#solution').wysihtml5(
					  {
						  "font-styles": true, //Font styling, e.g. h1, h2, etc. Default true
							"emphasis": true, //Italics, bold, etc. Default true
							"lists": true, //(Un)ordered lists, e.g. Bullets, Numbers. Default true
							"html": false, //Button which allows you to edit the generated HTML. Default false
							"link": true, //Button to insert a link. Default true
							"image": true, //Button to insert an image. Default true,
							"color": true //Button to change color of font
					  }		
					);
					return this;
				 },
				 inputError:function(model,response){
					if(response.responseText){
						alert('error2');
					}
					console.log(response);
				 },
				 submitIdear:function(){
					 var curEL=this.el;
						var form=$('#createIdearForm');
						this.model=new IdearModel();
						this.model.bind('error',this.inputError,this);
						this.$('[name=_wysihtml5_mode]').remove();
						this.model.save(form.serializeJSON(),{
							success:function(dd){
							$('#cancelBtn').click();
							$(curEL).hide();
							var newIdear=new IdearShowPanel({model:dd});
							$('#IdearsCenter').append(newIdear.render().el);
						}});
				},
			    open:function(name){
			    	name == "IdearCreation" ? this.render().$el.show(): this.$el.hide();
			    }
			 });
			
			var IdearShowPanel=Backbone.View.extend({
				 tagName:"div",
				 template:_.template(IdearModuleTemplate),
				 initialize: function (){
					this.addCommentView=new AddCommentView();
					this.commList=new CommentListView({model:this.model});
					idearContext.on(eventsName.shiftPanel,this.open,this);
				 },
				 render:function(){
					 $(this.el).html(this.template({"tempId":"IdearView","data":this.model.toJSON()}));
					 this.addCommentView.model=this.model;
					 $(this.el).append(this.addCommentView.render().el);
					 this.commList.model=this.model;
			    	 $(this.el).append(this.commList.render().el);
			    	 this.$el.show();
					 return this;
				 },
				 open:function(name,idearId){
				    	name == "IdearShown" ? this.showById(idearId): this.$el.hide();
				 },
				 showById:function(idearId){
					 this.model=new IdearModel({"id":idearId});
					 var cur=this;
					 this.model.fetch({
						 success:function(){
							 cur.render();
						 },
						 error:function(){
							 alert("Error when retrieve idear");
						 }
					 });
				 }
			});
			
			var AddCommentView=Backbone.View.extend({
				tagName:"div",
				template:_.template(IdearModuleTemplate),
				events:{
				  'click .textarea':"focusArea",
				  'click [type=button]':"submitComment"
				},
				initialize: function(){
				},
				render:function(){
					 $(this.el).html(this.template({"tempId":"AddComment","data":null}));
					return this;
				},
				focusArea:function(e){
					e.stopPropagation();
					this.textAreaObj=$(e.srcElement).wysihtml5();
				},
				submitComment:function(e){
					var idearId=this.model.get("idearId");
					var textArea=this.textAreaObj;
					var comment=new CommentModel({
						"idearId":this.model.get("idearId"),
						"comment":$(textArea).val()
					});
					comment.save({
						success:function(){
							$(textArea).data().wysihtml5.editor.clear();
							idearContext.trigger(eventsName.refreshComment);
						},
						error:function(){
							alert("error");
						}
					});
					
				}
			});
			
			var CommentView=Backbone.View.extend({
				tagName:"div",
				template:_.template(IdearModuleTemplate),
				initialize: function (){
					this.model.bind("destroy",this.remove,this);
				 },
				 render:function(){
					 $(this.el).html(this.template({"tempId":"CommentListItem","data":this.model.toJSON()}));
					 return this;
				 }
			});
            var CommentListView=Backbone.View.extend({
            	tagName:"div",
            	template:_.template(IdearModuleTemplate),
				initialize:function(model){
					this.commList=new CommentList();
					 this.commList.bind("add",this.addOne,this);
					 this.commList.bind("reset",this.addAll,this);
					 idearContext.on(eventsName.refreshComment,this.refresh,this);
				 },
				 render:function(){
					 $(this.el).html(this.template({"tempId":"CommentList","data":null}));
					 this.commList.idearId=this.model.get("idearId");
					 this.refresh();
					 return this;
				 },
				 addOne:function(cModel){
					 var commView=new CommentView({model:cModel});
					 $(this.el).append(commView.render().el);
				 },
				 addAll:function(){
					 this.$('ul').empty();
					 this.commList.each(this.addOne,this); 
				 },
				 refresh:function(){
					 this.commList.fetch();
				 }
			});
			return IdearModule;
		});